<template>
  <div style="padding:10px;height:100%; ">
    <div style="color:white;font-size:15pt;margin-bottom:10px">{{this.cate}}</div>
    <SearchDialog
      :name="name"
      :cate="cate"
      @beginSearch="onBeginSearch"
      :dialogVisible.sync="searchDlgVisible"
    />
    <el-form :inline="true">
       <el-form-item >
        <el-select
          placeholder="请选择年份"
          @change="loadTable"
          v-model="year"
          clearable
        >
          <el-option
           
            label="2019"
            value="2019"
          />
           <el-option
           
            label="2020"
            value="2020"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="isAdmin && isInput">
        <el-button
          type="primary"
          @click="viewDelete"
          icon="delete"
        >恢复删除</el-button>
      </el-form-item>
      <el-form-item v-if="isInput">
        <el-button
          type="primary"
          @click="edit"
          icon="delete"
        >编辑</el-button>
      </el-form-item>
      <el-form-item v-if="isInput">
        <el-button
          type="primary"
          @click="add"
          icon="delete"
        >增加</el-button>

      </el-form-item>
      <el-form-item v-if="isInput">
        <el-button
          type="primary"
          @click="remove"
          icon="delete"
        >删除</el-button>
      </el-form-item>
      
      <el-form-item v-if="isAudit">
        <el-button
          type="primary"
          @click="auditing"
          icon="delete"
        >审核</el-button>

      </el-form-item>
       <el-form-item v-if="isAudit">
        <el-button
           type="primary"
          @click="auditall"
          icon="delete"
        >一键审核</el-button>
      </el-form-item>
      <el-form-item v-if="!single">
        <el-button
          type="primary"
          @click="exportExcel"
          icon="export"
        >导出</el-button>
      </el-form-item>
      <el-form-item v-if="isInput  && !single">
        <el-upload
          class="upload-demo"
          :show-file-list="false"
          action=""
          :on-change="readExcel"
          :auto-upload="false"
        >
          <el-button type="primary">导入</el-button>
        </el-upload>
      </el-form-item>

      <el-form-item v-if="isInput && !single">
        <el-button
          type="primary"
          @click="downloadFile"
        >下载导入模板</el-button>
      </el-form-item>
      
      <el-form-item>
        <el-button
          type="primary"
          @click="search"
        >搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="resetSearch"
        >重设搜索结果</el-button>
      </el-form-item>
      <el-form-item v-if="isAudit">
        <el-select
          placeholder="请选择录入部门"
          @change="changeInputDep"
          v-model="inputDep"
          clearable
        >
          <el-option
            v-for="item in inputDeps"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="isInput" >
        <el-button
          type="primary"
          @click="flush"
          icon="export"
        >重新汇总</el-button>
      </el-form-item>
      <el-form-item v-if="isAudit">
        <el-select
          placeholder="请选择审核状态"
          @change="changeAuditStatus"
          v-model="auditStatus"
          clearable
        >

          <el-option
            label="不通过"
            value="不通过"
          />
          <el-option
            label="通过"
            value="通过"
          />
          <el-option
            label="待审核"
            value="待审核"
          />
        </el-select>
      </el-form-item>
     
    <el-form-item v-if="isInput">
        <el-button
         type="danger"
          @click="removeall"
          icon="delete"
        >全部删除</el-button>
      </el-form-item>
    </el-form>

    <el-table
      show-summary
      max-height="700"
      @sort-change='tableChange'
      :summary-method="getSummaries"
      :data="list"
      v-loading="listLoading"
      element-loading-text="Loading"
      ref="table"
      @selection-change="changeFun"
      border
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        class="selection"
        prop='uuid'
      ></el-table-column>
      <el-table-column
        align="center"
        width="50"
        label="序号"
      >
        <template slot-scope="scope">
          <span>{{(currentPage- 1) * pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        width="100"
        prop="建立姓名"
        sortable="custom"
        label="采集人"
      >
        <template slot-scope="scope">
          <span>{{scope.row.建立姓名}}</span>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        width="100"
        prop="审核姓名"
        sortable="custom"
        label="审核人"
      >
        <template slot-scope="scope">
          <span>{{scope.row.审核姓名}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        width="200"
        prop="审核状态"
        sortable="custom"
        label="审核状态"
      >
        <template slot-scope="scope">
          <el-tooltip
            placement="top"
            v-if="scope.row.审核状态=='不通过'"
          >
            <div slot="content">{{scope.row.审核意见}}<br />{{new Date(scope.row.审核时间).toLocaleString()}}</div>
            <span>{{scope.row.审核状态}}</span>
          </el-tooltip>
          <span v-else>{{scope.row.审核状态}}</span>

        </template>
      </el-table-column>

      <DataListItem
        v-bind:key="$index"
        v-for="(item,$index) in cols"
        :column="item"
      />
    </el-table>

    <el-pagination
      align="right"
      style="margin-top:20px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[20, 50, 100, 150, 200,500,1000]"
      :page-size="pageSize"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalPage"
    >
    </el-pagination>
    <EditDlg
      :groupCheck="groupCheck?groupCheck:[]"
      :data="this.model"
      v-if="showEditDlg"
      :cate="cate"
      :cancel.sync="showEditDlg"
      :ok.sync="showEditDlg"
      v-on:add="onadd"
      v-on:update="onupdate"
      :mode="editMode"
    />
    <el-dialog
      title="出错提示"
      :close-on-click-modal="false"
      :visible="errDlg"
      @close="onclosedlg"
    >
    
      <el-table :data="errorData"  max-height="400" >
        <el-table-column
          align="center"
          prop="行号"
          label="行号"
        />
        <el-table-column
          align="center"
          width="100"
          label="错误描述"
        ><template slot-scope="scope"><span style="color: red">{{scope.row.error}}</span>
          </template></el-table-column>
        <DataListItem
          v-bind:key="$index"
          v-for="(item,$index) in cols"
          :column="item"
        />

      </el-table>
   
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="exportErr"
        >导出</el-button>
        <el-button
          type="primary"
          @click="onclosedlg"
        >确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="还原数据"
    
      :close-on-click-modal="false"
      :visible="deleteDlg"
      @close="onclosedlg"
    >

      <el-table
        max-height="400"
        @selection-change="changeDeleteFun"
        :data="deleteData"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          class="selection"
          prop='uuid'
        ></el-table-column>
        <DataListItem
          v-bind:key="$index"
          v-for="(item,$index) in cols"
          :column="item"
        />

      </el-table>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="onCloseDeleteDlg"
        >还原</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="审核"
      :close-on-click-modal="false"
      :visible="auditDlg"
      @close="onclosedlg"
    >
      <el-form>
        <el-form-item label="审核意见">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="审核意见"
            v-model="auditDesc"
          />
        </el-form-item>

      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="onAuditPass('不通过')"
        >不通过</el-button>
        <el-button
          type="primary"
          @click="onAuditPass('通过')"
        >通过</el-button>
        <el-button
          type="primary"
          @click="onclosedlg "
        >取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="提交数据"
      center="true"
      width="30%"
      :close-on-click-modal="false"
      :visible="submitDlg"
      @close="onclosedlg"
    >

      <!-- <el-table
        height="600"
       v-loading="dataListLoading"
        :data="submitData"
      >
       
        <DataListItem
          v-bind:key="$index"
          v-for="(item,$index) in cols"
          :column="item"
        />

      </el-table> -->
      
      <h3>已经发现{{submitData.length}}条数据,是否上传?</h3>
      <br/>
      <el-form>
        <el-form-item label="上传方式">
          <el-select v-model="uploadMethod">
            <el-option value="追加上传"  label="追加上传"></el-option>
            <el-option value="清空上传" label="清空上传"></el-option>
            
          </el-select>

        </el-form-item>
        
        <!-- <el-form-item label="审核状态">
           <el-select v-model="uploadAudit">
            <el-option value="待审核" label="待审核"></el-option>
            <el-option value="通过" label="通过"></el-option>
            
          </el-select>

        </el-form-item> -->
        
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="onclosedlg"
        >取消</el-button>
        <el-button
          type="primary"
          @click="submitMyData"
        >提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Vue from "vue";
import request from "@/utils/request";
import { setSaveAfter2019 } from "@/api/案例分析.js";
import { getUser } from "@/utils/auth";
import { getPage, getRemoveData, removeAllData,auditAllData } from "@/api/分页";
import { getSummary } from "@/api/统计";
import EditDlg from "@/components/EditDlg";
import SearchDialog from "@/components/SearchDialog";
import linq from "linq";
import { getLock } from "@/api/权限";
import axios from "axios";
import { uuid } from "vue-uuid";
import { defer } from "q";
import { debug, debuglog } from "util";
export default {
  props: [
    "cols",
    "cate",
    "name",
    "addQuery",
    "single",
    "groupCheck",
    "skipExcelNumber",
    "excelHeader"
  ],
  components: {
    EditDlg,
    SearchDialog,
    DataListItem: {
      name: "DataListItem",
      template: `<el-table-column  :sortable="column.data?null:'custom'"   :label='column.label' :prop='column.prop' align="center">
          <DataListItem :key="$index" v-for="(item,$index) in column.data?column.data:[]" :column="item" />
          </el-table-column>
          `,
      props: ["column"]
    }
  },
  data: function() {
    return {
      searchDlgVisible: false,
      inputDep: "",
      auditStatus: "",
      importModel: "1",
      inputDeps: [],
      uploadMethod:'追加上传',
      uploadAudit:'待审核',
      model: {},
      showEditDlg: false,
      dataListLoading: false,
      deleteDlg: false,
      importAskDlg: false,
      deleteData: [],
      errorData: [],
      totalPage: 0,
      errDlg: false,
      submitData: [],
      submitDlg: false,
      isInput: false,
      isAudit: false,
     
      isAdmin: false,
      oneKeyAudit:false,
      isView: false,
      auditDesc: "",
      fileTemp: null,
      sums: [],
      year:'2020',
      listLoading: true,
      list: [],
      pageHelp: { limit: 20, page: 0 },
      raw: [],
      multipleSelectionDelete: [],
      multipleSelection: [],
      currentPage: 1,

      auditDlg: false,
      editMode: "add",
      pageSize: 20,
      user: null,
      query: "",
      order: "建立时间"
    };
  },
  mounted() {
    var that = this;
  },
  async created() {
    //
    this.user = getUser();
    this.isAdmin = this.user.ROLE_INPUT == "admin";
    this.isInput = this.$route.query.mode == "input";
    this.isAudit = this.$route.query.mode == "audit";

    this.isView = this.$route.query.mode == "view";
    //
    await this.loadTable();

    //
    //
    
    this.inputDeps = linq
      .from(this.$root.教师基本情况)
      .join(this.list, "$.GH", "$.建立卡号", "$.BMMC")
      .distinct()
      .toArray();
    //.distinct("$.BMMC").toArray();
    this.inputDeps.push("管理员");
    var j = 3;
    this.listLoading = false;

    //
  },

  methods: {
    async resetSearch() {
      this.query = "";
      this.currentPage = 1;
      this.pageHelp.limit = 20;
      this.pageHelp.page = (this.currentPage - 1) * this.pageSize;
      this.order = "ID Desc";
      await this.loadTable();
    },
    clickImport() {
      ;
      this.importAskDlg = true;
    },
    async flush() {
    try {
      this.listLoading = true;
      var user = getUser();
      await setSaveAfter2019(user.XXID, user.CJPC);
        this.listLoading = false;
    } catch (e) {
      this.$alert(e);
    }
  }, 
    search() {
      this.searchDlgVisible = true;
    },
    async loadTable() {
      this.listLoading = true;

      var res = await getPage(
        this.name,
        this.$root.user.XXID,
        this.year,
        this.pageHelp,
        this.query,
        this.order,
        this.isView ? "是" : "",
        this.addQuery
      );

      this.totalPage = res.total;
      this.list = res.values;
      this.sums = res.sums ? res.sums : [];
      this.$parent.onFetchData ? this.$parent.onFetchData(this.list) : "";
      this.listLoading = false;
    },
    async onBeginSearch(sql) {
      this.listLoading = true;
      this.query = sql;
      this.currentPage = 1;
      await this.loadTable();
      this.listLoading = false;
      var j = 2;
    },
    tableChange: function(column, prop, order) {
      if (column.order == "descending") {
        this.order = column.prop + " DESC";
      } else {
        this.order = column.prop + " ASC";
      }
      this.loadTable();
    },
    getSummaries(param) {
      //
      return this.sums;
      //
    },
    downloadFile() {
      axios
        .get(process.env.BASE_SERVER + "template/template.xlsx", {
          responseType: "blob"
        })
        .then(({ data }) => {
          let blob = new Blob([data], { type: "application/octet-stream" });
          let link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = "template.xlsx";
          link.click();
        });
    },
    changeFun(val) {
      this.multipleSelection = val;
    },
    changeDeleteFun(val) {
      this.multipleSelectionDelete = val;
    },
    handleSizeChange: function(size) {
      this.pageSize = size;

      this.pageHelp.limit = this.pageSize;
      this.pageHelp.page = (this.currentPage - 1) * this.pageSize;
      this.loadTable();
    },

    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage;
      this.pageHelp.page = (this.currentPage - 1) * this.pageSize;
      this.loadTable();
    },
    async viewDelete() {
      //
      try {
        var lock = await this.isLock();
        if (lock) {
          this.$alert("此表已经锁定,无法删除或修改");
          return;
        }   
        let datas = await this.$parent.fetchData();
        this.deleteData = datas.filter(e => e.是否删除 == 1);
        this.deleteDlg = true;
      } catch (e) {
        this.$alert(e);
      }
    },

    exportErr() {
      var XLSX = require("xlsx");
      var schema = require("@/schema/" + this.cate + ".json");
      this.errorData = this.errorData.map(e => {
        var s = {};

        Object.keys(e).forEach(k => {
          if (k == "行号" || k == "error") {
            s[k] = e[k];
          } else
          if(schema.properties[k])
           s[schema.properties[k].title] = e[k];
           else
           return
        });
        return s;
      });
      var ws = XLSX.utils.json_to_sheet(this.errorData);
      var wb = XLSX.utils.book_new(); /*新建book*/
      XLSX.utils.book_append_sheet(
        wb,
        ws,
        "错误数据"
      ); /* 生成xlsx文件(book,sheet数据,sheet命名) */
      XLSX.writeFile(wb, "错误数据.xlsx"); /*写文件(book,xlsx文件名称)*/
    },
    async aduitall(){
      //
      this.auditDlg = true;
      //
    },
    async removeall() {
      await this.$confirm("你决定删除所有数据吗?由于不可恢复,请删除前先导出作为备分");
      
      await removeAllData(
         this.$root.user.GH,
        this.$root.user.XM,
        this.name,
        this.$root.user.XXID,
        this.$root.user.CJPC,
        this.cate=='A6校内教师基本情况表'?("(教师性质='校内专任' or 教师性质='校内兼课' or 教师性质='其他')"):
        (this.cate=='A6校外教师基本情况表'?("(教师性质='校外兼职' or 教师性质='校外兼课')"):null)
      );
      this.loadTable();
    },
    async exportExcel() {
      //
      var that = this;

      axios
        .get(process.env.BASE_SERVER + "template/template.xlsx", {
          responseType: "blob"
        })
        .then(async res => {
          console.log("begin download");
          that.listLoading = false;
          let blob = new Blob([res.data]);
          var buffer = await new Response(blob).arrayBuffer();
          var XLSX = require("xlsx");
          var data = new Uint8Array(buffer);
          var wb = XLSX.read(data, { type: "array" });
          var schema = require("@/schema/" + that.cate + ".json");
          var props = Object.keys(schema.properties).map(
            p => schema.properties[p].title
          );
          var keys = Object.keys(schema.properties);
          var result = [];
          that.listLoading = true;

          that.pageHelp = { limit: 999999, page: 0 };

          var res = await getPage(
            that.name,
            that.$root.user.XXID,
            that.$root.user.CJPC,
            that.pageHelp,
            that.query,
            this.order,
            this.isView ? "是" : "否",
            this.addQuery
          );
          var mylist = res.values;
          console.log("finish loadtable");
          
          mylist.forEach(item => {
            var data = [];
            console.log("write data");
            keys.forEach(e => {
              if (item[e] instanceof Array) {
                data.push(item[e].join("、"));
              } else {
                data.push(item[e]);
              }
            });
            result.push(data);
          });
          console.log("finish write data");
          XLSX.utils.sheet_add_aoa(wb.Sheets[that.cate], result, {
            origin: "B" + (parseInt(that.skipExcelNumber) + 2)
          });
          var wbout = XLSX.write(wb, {
            bookType: "xlsx",
            bookSST: false,
            cellStyles: false,
            type: "binary"
          });
          console.log(" write excel finish");
          function s2ab(s) {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff;
            return buf;
          }

          saveAs(new Blob([s2ab(wbout)], { type: "" }), "file.xlsx");
          that.listLoading = false;
          console.log("finish");
        });
      function saveAs(obj, fileName) {
        var tmpa = document.createElement("a");
        tmpa.download = fileName || "下载";
        tmpa.href = URL.createObjectURL(obj);
        tmpa.click();
        setTimeout(function() {
          URL.revokeObjectURL(obj);
        }, 100);
      }

      //
    },

    changeInputDep() {
      if (this.inputDep != "") {
        this.list = linq
          .from(this.list)
          .where(x => {
            if (this.inputDep != "管理员") {
              var t = linq
                .from(this.$root.教师信息)
                .first(`$.GH=='x.建立卡号'`);
              if (t) {
                return t.BMMC == this.inputDep;
              } else {
                return false;
              }
            } else {
              return x.建立姓名 == "管理员";
            }
          })
          .toArray();
      } else {
        this.loadTable();
      }
    },
    //选择审核状态
    changeAuditStatus() {
      //
      if (this.auditStatus == "") {
        this.loadTable();
      } else {
        this.list = this.list.filter(e => e.审核状态 == this.auditStatus);
      }
      //
    },
    async isLock() {
      var locks = await getLock(this.$root.user.XXID, this.$root.user.CJPC);
      var first = linq
        .from(locks)
        .firstOrDefault(`$.TABLENAME == '${this.name}'`);
      if (first && first.LOCK == "是") {
        return true;
      } else {
        return false;
      }
    },
    async readExcel(file) {
      //

      var lock = await this.isLock();
      if (lock) {
        this.$alert("此表已经锁定,无法删除或修改");
        return;
      }
      var that = this;
    
      const fileReader = new FileReader();
      fileReader.onload = async ev => {
      // try {
          this.listLoading = true;

          const data = ev.target.result;
          var XLSX = require("xlsx");
          const workbook = XLSX.read(data, {
            type: "binary"
          });
          var schema = require("@/schema/" + this.cate + ".json");
          var props = Object.keys(schema.properties);
          props.unshift("temp");
          const sheetArray = XLSX.utils.sheet_to_json(
            workbook.Sheets[this.cate],
            { header: props, defval: "" }
          );
          //模板合法性检查
          
          var sheet = workbook.Sheets[this.cate];
          if (sheet == undefined) {
            
            throw "请使用正常的模板上传数据";
          }

          if (sheet["A1"] && sheet["A1"].v !== "示例") {
              
            throw "请使用正常的模板上传数据";
          }

          Object.keys(that.excelHeader).forEach(item => {
           if(!sheet[item]){
                 
               throw "请使用正常的模板上传数据";
           }
          
            var temp = sheet[item].v
              .replace(/[\r\n]/g, "")
              .replace("（", "(")
              .replace("）", ")"); //去掉回车行
            var temp1 = that.excelHeader[item]
              .replace(/[\r\n]/g, "")
              .replace("（", "(")
              .replace("）", ")");
            if (temp !== temp1) {
              
              throw "请使用正常的模板上传数据";
            }
          });

          //
          linq.from(sheetArray).forEach((e, i) => {
            delete e.temp;
            e["行号"] = i;
          });

          sheetArray.splice(0, this.skipExcelNumber);
          //
        
   sheetArray.forEach((e, index) => {
            Object.keys(e).forEach(p => {
              
              //检测必须数据是否空白
              e[p] = e[p] + "";
              e[p] = e[p].trim();
            })});
          this.submitData = sheetArray;
           
          this.pageHelp = { limit: 999999, page: 0 };
          var res = await getPage(
            that.name,
            that.$root.user.XXID,
            that.$root.user.CJPC,
            that.pageHelp,
            "",
            "ID",
            "是"
          );
          var mylist = res.values;
          
          await this.$parent.check(this.submitData, mylist);
          var schema = require("@/schema/" + this.cate + ".json");
          //单元格开始检查
           
          sheetArray.forEach((e, index) => {
            Object.keys(e).forEach(p => {
              if(!schema.properties[p])
                return;
              if (p == "行号") return;
              //检测必须数据是否空白

             
              if (e[p] === "") {
                
                 if(schema.required.indexOf(p) !==-1)
                {
                    
                     e.error = e.error
                        ? e.error + ";"
                        : "" +
                          schema.properties[p].title +
                          "字段的值不能为空值";
                      return;
                }else
                  delete e[p];
              } else {
                //检查是否在范围内
                
               
            
                if (
                  schema.properties[p].enum &&
                  schema.properties[p].enum.length > 0 &&
                  schema.properties[p].enum[0].trim() !== "" &&
                  schema.properties[p].enum.findIndex(item =>item==e[p]) == -1
                ) {
                   
                  e.error = e.error
                    ? e.error + ";"
                    : "'" +
                      schema.properties[p].title +
                      "'字段的值不在规定的范围内,该字段只能取如下值:" +
                      schema.properties[p].enum.join("、");
                  return;
                }
                if (
                  schema.properties[p].attrs &&
                  schema.properties[p].attrs.type == "date"
                ) {
                  if (schema.properties[p].attrs.format == "yyyyMM") {
                    if (/^\b[1-3]\d{3}(0[1-9]|1[0-2])$/.test(e[p]) == false) {
                       
                      e.error = e.error
                        ? e.error + ";"
                        : "" +
                          schema.properties[p].title +
                          "不满足规定的时间格式,格式为yyyyMM";
                      return;
                    }
                  }
                  if (schema.properties[p].attrs.format == "yyyyMMdd") {
                    if (
                      new RegExp(
                        "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|" +
                          "(02(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229)"
                      ).test(e[p]) == false
                    ) {
                       
                      e.error = e.error
                        ? e.error + ";"
                        : "" +
                          schema.properties[p].title +
                          "不满足规定的时间格式,格式为yyyyMMdd";
                      return;
                    }
                  }
                }
                if (
                  schema.properties[p].maxLength &&
                  e[p].length > schema.properties[p].maxLength
                ) {
                   
                  e.error = e.error ? e.error + ";":schema.properties[p].title + "长度超过字符串规定的最大长度";
                  return;
                }
                //检查正则表达式 ,长度,类型,格式
                
              
                if (
                  schema.properties[p].pattern &&
                  new RegExp(schema.properties[p].pattern).test(e[p]) == false
                ) {
                   
                  e.error = e.error
                    ? e.error + ";"
                    : "" + schema.properties[p].title + "不满足规定的格式,数字如果是公式计算,请使用round函数保留小数点后5位";
                  return;
                }
              }
            });
          });
          this.errorData = linq
            .from(this.submitData)
            .where(e => e.error !== undefined)
            .toArray();
          this.listLoading = false;
          if (this.errorData.length > 0) {
            this.errDlg = true;
          } else {
          
            this.uploadMethod="追加上传";
            this.uploadAudit ="待审核"
            this.submitDlg=true;
      
          }
        // } catch (e) {
        //   this.$alert(e);
        // }finally{
        //   this.listLoading=false;
        // }
      };

      fileReader.readAsBinaryString(file.raw);
    },
    async submitMyData(){
        
         this.submitDlg=false;
         this.listLoading=true;
                if(this.uploadMethod == "清空上传"){
                   await removeAllData(
                        this.$root.user.GH,
          this.$root.user.XM,
                    this.name,
                    this.$root.user.XXID,
                    this.$root.user.CJPC,
                       this.cate=='A6校内教师基本情况表'?("(教师性质='校内专任' or 教师性质='校内兼课' or 教师性质='其他')"):
        (this.cate=='A6校外教师基本情况表'?("(教师性质='校外兼职' or 教师性质='校外兼课')"):null)
   
                  );
                }
            
            var user = getUser();
            this.submitData.forEach(e => {
              e.ID = uuid.v1();
              delete e.行号;
              e.CJPC = user.CJPC;
              e.XXID = user.XXID;
              e.建立卡号 = user.GH;
              e.建立姓名 = user.XM;
              e.建立时间 = new Date().toISOString();
              e.审核状态 = "待审核"
              e.是否删除 = 0;
            });
                await this.$parent.bulkAdd(this.submitData);

                this.$alert("上传数据成功");
                await this.resetSearch();
                //this.loadTable();
               
                this.listLoading = false;
    },
    async add() {
      var lock = await this.isLock();
      if (lock) {
        this.$alert("此表已经锁定,无法删除或修改");
        return;
      }
      if (this.single && this.list.length > 0) {
        this.$alert("只能创建一条记录");
        return;
      }

      this.editMode = "add";

      this.model = {};
      this.showEditDlg = true;
      this.$nextTick(_ => {
        this.$parent.onDlgCreated ? this.$parent.onDlgCreated() : "";
      });
    },
    onclosedlg() {
      this.deleteDlg = false;
      this.errDlg = false;
      this.auditDlg = false;
      this.importAskDlg = false;
      this.submitDlg = false;
    },

    async onCloseDeleteDlg() {
        //  try {
        var locks = await getLock(this.$root.user.XXID, this.$root.user.CJPC);
        var first = linq
          .from(locks)
          .firstOrDefault(`$.TABLENAME == '${this.name}'`);
        if (first && first.LOCK == "是") {
          this.$alert("此表已经锁定,无法删除或修改");
          return;
        }
       
        await Promise.all(
          this.multipleSelectionDelete.map(async (item, index) => {
            item.是否删除 = 0;
            await this.$parent.onupdate(item);
          })
        );
        this.deleteDlg = false;
        await this.loadTable();
       
        this.listLoading = false;
      // } catch (e) {
      //   this.$alert(e);
      // }
    },
    async onchange(model, field, e) {
      this.$parent.onChange ? this.$parent.onChange(model, field, e) : "";
    },
    // onDlgCreated() {
    //  this.$parent.onDlgCreated? this.$parent.onDlgCreated(this.model) : ""
    // },
   
    async onadd(model) {
      try {
        var user = getUser();
        model.ID = uuid.v1();
        model.CJPC = user.CJPC;
        model.XXID = user.XXID;
        model.建立卡号 = user.GH;
        model.建立姓名 = user.XM;
        model.建立时间 = new Date().toISOString();
        model.审核状态 = "待审核";
        model.是否删除 = 0;
        var keys = Object.keys(model);
        //删除空值
     
        keys.forEach(k => {
          if (model[k] === null) {
            delete model[k];
          }
          if (model[k] === "") {
            delete model[k];
          }
        });

        if (this.$parent.add_check) {
          var ss = this.$parent.add_check(model, this.list);
          if (ss) throw ss;
        }
        
        var result = await this.$parent.onadd(model);
        this.list.unshift(result);
        this.showEditDlg = false;
      } catch (e) {
        this.$alert(e);
      }
    },
    async onupdate(model) {
      try {
        model.审核状态 = "待审核";
        var keys = Object.keys(model);
        keys.forEach(k => {
          if (model[k] == null) {
            delete model[k];
          }
          if (model[k] == "") {
            delete model[k];
          }
        });

        await this.$parent.onupdate(model);

        this.showEditDlg = false;
        this.$set(this.list, this.editIndex, model);
      } catch (e) {
        this.$alert(e);
      } finally {
        this.clearSelection();
      }
    },
    async edit() {
      try {
        var lock = await this.isLock();
        if (lock) {
          throw "此表已经锁定,无法删除或修改";
        }

        if (
          this.multipleSelection.length == 0 ||
          this.multipleSelection.length > 1
        ) {
          throw "请选中一条数据进行编辑";
        }

        this.model = JSON.parse(JSON.stringify(this.multipleSelection[0]));
        this.editIndex = this.list.findIndex(e => {
          return e.ID == this.model.ID;
        });

        // if (
        //   this.model.建立卡号 &&
        //   this.$root.user.GH !== this.model.建立卡号 &&
        //   this.isAdmin == false
        // ) {
        //   throw "你不是该条数据的创建者,不能编辑";
        // }
        this.editMode = "update";
        this.showEditDlg = true;
        Object.keys(this.model).map(item => {
          if (typeof this.model[item] == "number") {
            this.model[item] = this.model[item].toString();
          }
        });

        this.$nextTick(_ => {
          this.$parent.onDlgCreated ? this.$parent.onDlgCreated() : "";
        });
      } catch (e) {
        this.$alert(e);
      } finally {
      }
    },
    auditall(){
      this.oneKeyAudit= true;
       this.auditDlg  = true;
    },
    async onAuditPass(desc) {
      try {
        var lock = await this.isLock();
        if (lock) {
          this.$alert("此表已经锁定,无法删除或修改");
          return;
        }
        this.auditDlg = false;
        this.listLoading = true;
        if(this.oneKeyAudit == false){
        await Promise.all(
          this.multipleSelection.map(async (item, index) => {
            item.审核状态 = desc;
            item.审核时间 = new Date().toISOString();
            item.审核卡号 = this.user.GH;
            item.审核意见 = this.auditDesc;
            item.审核姓名 = this.user.XM;
            await this.$parent.onupdate(item);
          })
        );
        }else{
          await auditAllData(this.user.GH,this.user.XM,desc,this.name,this.user.XXID,this.user.CJPC);
        }
        await this.loadTable();
        
         this.oneKeyAudit= false;
        this.listLoading = false;
        this.auditDesc = "";
      } catch (e) {
        this.$alert(e);
      } finally {
        this.clearSelection();
      }
    },
    clearSelection() {
      this.$refs.table.clearSelection();
    },
    auditing() {
      if (this.multipleSelection.length == 0) {
        this.$alert("请选中至少一条数据进行审核");
        return;
      }
      //
      this.auditDlg = true;
      //
    },

    async remove() {
      var lock = await this.isLock();
      if (lock) {
        this.$alert("此表已经锁定,无法删除或修改");
        return;
      }
      try {
        this.multipleSelection.forEach((item, index) => {
          if (
            item.建立卡号 &&
            this.$root.user.GH !== item.建立卡号 &&
            this.isAdmin == false
          ) {
            throw "你不是选中的第" + index + "条数据的创建者,不能删除";
          }
        });
        this.$confirm("你确定是否删除").then(async e => {
          var user = getUser();
          this.multipleSelection.forEach((item, index) => {
            if (item.审核状态 == "通过" && this.$root.user.XM !== "管理员") {
              throw "无法删除,选中记录存在已经审核通过的记录,";
            }
          });
          this.listLoading = true;
          await Promise.all(
            this.multipleSelection.map(async (item, index) => {
              item.是否删除 = 1;
              item.删除卡号 = user.GH;
              item.删除姓名 = user.XM;
              item.删除时间 = new Date().toISOString();
              await this.$parent.onupdate(item);
            })
          );
          //
          await this.loadTable();
          //
          this.listLoading = false;
        });
      } catch (e) {
        this.$alert(e);
        this.clearSelection();
      }
    }
  }
};
</script>
<style >
.el-table td,
.el-table th.is-leaf {
  border: 1px solid black;
}

.el-table--border th,
.el-table--border th.gutter:last-of-type {
  border: 1px solid;
}

.el-table--border td,
.el-table--border th {
  border: 1px solid;
}
</style>